// Package eventbus 基于map的事件总线实现
package eventbus

import (
	"fmt"
	"organoid_public/pkg/logger"
	"sync"
)

// EventManager 事件管理器
type EventManager struct {
	handlers map[EventType]map[EventHandlerID]EventHandler
	mu       sync.RWMutex
	log      logger.Logger
}

// NewEventManager 实例化
func NewEventManager(log logger.Logger) *EventManager {
	return &EventManager{
		handlers: make(map[EventType]map[EventHandlerID]EventHandler),
		log:      log,
	}
}

// Subscribe 订阅某个事件的处理函数
func (em *EventManager) Subscribe(eventType EventType, handlerID EventHandlerID, handler EventHandler) {
	em.mu.Lock()
	defer em.mu.Unlock()

	if _, ok := em.handlers[eventType]; !ok {
		em.handlers[eventType] = make(map[EventHandlerID]EventHandler)
	}

	em.handlers[eventType][handlerID] = handler
}

// Unsubscribe 取消订阅某个事件的处理函数
func (em *EventManager) Unsubscribe(eventType EventType, handlerID EventHandlerID) {
	em.mu.Lock()
	defer em.mu.Unlock()

	if _, ok := em.handlers[eventType]; ok {
		delete(em.handlers[eventType], handlerID)
	}
}

// Emit 触发某个事件
func (em *EventManager) Emit(eventType EventType, data interface{}) {
	em.mu.RLock()
	defer em.mu.RUnlock()

	event := &Event{
		Type: eventType,
		Data: data,
	}

	if handlers, ok := em.handlers[eventType]; ok {
		var wg sync.WaitGroup
		errs := make(chan error, len(handlers))

		//并发执行所有订阅
		for id, handler := range handlers {
			wg.Add(1)
			go func(id EventHandlerID, h EventHandler) {
				defer wg.Done()
				err := h(event)
				if err != nil {
					errs <- fmt.Errorf("事件类型: %s, 事件处理器ID：%s, 错误：%s", eventType, id, err.Error())
				}
			}(id, handler)

		}

		wg.Wait()
		close(errs)

		// 处理错误
		for err := range errs {
			em.log.Error("event", err.Error())
		}
	}

}

// StartListening 开始事件监听
func (em *EventManager) StartListening(opts ...Subscribe) {
	for _, opt := range opts {
		opt.SubscribeRegister()
	}
}
